# 导入 Pygame 模块和必要的库：
import pygame
import random
# 初始化 Pygame：
pygame.init()
# 设置游戏窗口的宽度和高度：
width, height = 640, 480
screen = pygame.display.set_mode((width, height))
# 定义贪吃蛇的初始位置和移动方向：
snake_pos = [100, 50]
snake_body = [[100, 50], [90, 50], [80, 50]]
direction = "RIGHT"
# 定义蛇的移动速度、食物的位置和分数：
snake_speed = 10
food_pos = [random.randrange(1, width // 10) * 10, random.randrange(1, height // 10) * 10]
food_spawn = True
score = 0
# 创建游戏主循环，处理事件和更新游戏状态：
while True:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
            exit(0)
    # 处理按键事件，改变蛇的移动方向：
        elif event.type == pygame.KEYDOWN:
            if event.key == pygame.K_RIGHT:
                direction = "RIGHT"
            if event.key == pygame.K_LEFT:
                direction = "LEFT"
            if event.key == pygame.K_UP:
                direction = "UP"
            if event.key == pygame.K_DOWN:
                direction = "DOWN"
    # 更新贪吃蛇的位置和身体：
    if direction == "RIGHT":
        snake_pos[0] += 10
    if direction == "LEFT":
        snake_pos[0] -= 10
    if direction == "UP":
        snake_pos[1] -= 10
    if direction == "DOWN":
        snake_pos[1] += 10
    
    snake_body.insert(0, list(snake_pos))
    
    if snake_pos[0] == food_pos[0] and snake_pos[1] == food_pos[1]:
        score += 1
        food_spawn = False
    else:
        snake_body.pop()
    # 检查贪吃蛇是否碰到边界或自己的身体：
    if snake_pos[0] < 0 or snake_pos[0] > width-10:
        pygame.quit()
        exit(0)
    if snake_pos[1] < 0 or snake_pos[1] > height-10:
        pygame.quit()
        exit(0)
    for block in snake_body[1:]:
        if snake_pos[0] == block[0] and snake_pos[1] == block[1]:
            pygame.quit()
            exit(0)
    # 生成新的食物：
    if not food_spawn:
        food_pos = [random.randrange(1, width // 10) * 10, random.randrange(1, height // 10) * 10]
        food_spawn = True
    # 渲染游戏界面：
    screen.fill((0, 0, 0))
    for pos in snake_body:
        pygame.draw.rect(screen, (0, 255, 0), pygame.Rect(pos[0], pos[1], 10, 10))
    pygame.draw.rect(screen, (255, 0, 0), pygame.Rect(food_pos[0], food_pos[1], 10, 10))
    pygame.display.set_caption("贪吃蛇游戏 - 得分: " + str(score))
    pygame.display.flip()
    # 控制游戏更新速度：
    pygame.time.Clock().tick(snake_speed)